package com.zqx.tokenauth.handler;


import com.zqx.tokenauth.auth.Authorization;
import com.zqx.tokenauth.entity.TokenModel;
import com.zqx.tokenauth.enums.TokenEnum;
import com.zqx.tokenauth.service.TokenManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * @author zqx
 * @date 2018.07.21
 */
@Component
public class AuthorizationInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private TokenManager manager;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 如果不是映射到方法直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        HandlerMethod handlerMethod = (HandlerMethod)handler;
        Method method = handlerMethod.getMethod();
        //从header中获取token
        String authorization = request.getHeader(TokenEnum.AUTHORIZATION.getMessage());
        //验证token
        TokenModel model = manager.getToken(authorization);
        if(manager.checkToken(model))
        {
            //如果token验证成功，将token对应的用户id存在request中
            request.setAttribute(TokenEnum.CURRENT_USER_ID.getMessage(),model.getUserId());
            return true;
        }
        //如果验证失败，并且方法注明了Authorization,返回401错误
        if(method.getAnnotation(Authorization.class) !=null)
        {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
        return true;
    }
}
